package com.silence.top_on_flutter

import android.app.Activity
import android.util.Log
import android.widget.Toast
import com.anythink.core.api.ATAdInfo
import com.anythink.core.api.AdError
import com.anythink.rewardvideo.api.ATRewardVideoAd
import com.anythink.rewardvideo.api.ATRewardVideoListener
import java.lang.ref.WeakReference

class ATRewardVideoUtil(private val activity: Activity,
                        private val placementId: String? = "a5faa0e149562c",
                        private val listener: ATRewardVideoListener?) : ATRewardVideoListener {

    private val activityRef = WeakReference(activity)

    private val mAd: ATRewardVideoAd = ATRewardVideoAd(activity, placementId)

    private var needShow = false

    init {
        mAd.setAdListener(listener ?: this)
        loadCache()
    }

    fun setListener(listener: ATRewardVideoListener): ATRewardVideoUtil {
        mAd.setAdListener(listener)
        return this
    }

    fun showAd(): ATRewardVideoUtil {
        activityRef.get()?.let {
            if (mAd.isAdReady) {
                needShow = false
                mAd.show(it)
            } else {
                needShow = true
                Toast.makeText(it, "重新加载", Toast.LENGTH_SHORT).show()
                mAd.load()
            }
        }
        return this
    }

    private fun loadCache() {
        if (!mAd.isAdReady) {
            mAd.load()
        }
    }

    //activity ondestroy
    fun onDestroy() {
        activityRef.clear()
    }

    override fun onRewardedVideoAdClosed(p0: ATAdInfo?) {
        Log.v("onRewarded", "onRewardedVideoAdClosed" + p0.toString())
        mAd.load()
    }

    override fun onReward(p0: ATAdInfo?) {
        Log.v("onRewarded", "onReward" + p0.toString())
    }

    override fun onRewardedVideoAdPlayFailed(p0: AdError?, p1: ATAdInfo?) {
        Log.v("onRewarded", "onRewardedVideoAdPlayFailed" + p0.toString())
    }

    override fun onRewardedVideoAdLoaded() {
        if (needShow) {
            showAd()
        }
        Log.v("onRewarded", "onRewardedVideoAdLoaded")
    }

    override fun onRewardedVideoAdPlayStart(p0: ATAdInfo?) {

        Log.v("onRewarded", "onRewardedVideoAdPlayStart" + p0.toString())
    }

    override fun onRewardedVideoAdFailed(p0: AdError?) {
        Log.v("onRewarded", "onRewardedVideoAdFailed" + p0.toString())
    }

    override fun onRewardedVideoAdPlayEnd(p0: ATAdInfo?) {

        Log.v("onRewarded", "onRewardedVideoAdPlayEnd" + p0.toString())
    }

    override fun onRewardedVideoAdPlayClicked(p0: ATAdInfo?) {

        Log.v("onRewarded", "onRewardedVideoAdPlayClicked" + p0.toString())
    }


}